
package com.eworking.eim.cloud;

import android.content.Context;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;

import com.eworking.eim.exception.EIMException;
import com.eworking.eim.util.NetUtil;
import com.eworking.util.EWoringLog;

public class HttpFileManager extends CloudFileManager {
    
    /** 日志输出标记 */
    private static final String _TAG = HttpFileManager.class.getSimpleName();
    
    /** 文件服务器地址 */
    private static String USER_SERVER_URL;
    
    private long totalSize = 0;
    
    private Context appContext;
    
    public HttpFileManager(Context context, String url) {
        this.appContext = context.getApplicationContext();
        if (url.startsWith("http"))
            USER_SERVER_URL = url;
        else
            USER_SERVER_URL = "https://" + url;
    }
    
    public boolean authorization() {
        return true;
    }
    
    public boolean sendFiletoServer(String paramString1, String paramString2, String paramString3, String paramString4,
        CloudOperationCallback paramCloudOperationCallback) throws EIMException {
        File localFile = new File(paramString1);
        if (!(localFile.isFile())) {
            EWoringLog.e("CloudFileManager", "Source file doesn't exist");
            paramCloudOperationCallback.onError("Source file doesn't exist");
            return false;
        }
        HttpURLConnection localHttpURLConnection = null;
        DataOutputStream localDataOutputStream = null;
        int i = 0;
        String str1 = "\r\n";
        String str2 = "--";
        String str3 = "*****";
        int i1 = NetUtil.getUploadBufSize(this.appContext);
        int i2 = (int) localFile.length();
        int i3 = 0;
        try {
            try {
                String str8;
                FileInputStream localFileInputStream = new FileInputStream(new File(paramString1));
                URL localURL = null;
                if (paramString4 != null)
                    localURL = new URL(USER_SERVER_URL + "/" + paramString4.replaceFirst("#", "/"));
                else
                    localURL = new URL(USER_SERVER_URL + paramString2);
                localHttpURLConnection = (HttpURLConnection) localURL.openConnection();
                localHttpURLConnection.setDoInput(true);
                localHttpURLConnection.setDoOutput(true);
                localHttpURLConnection.setUseCaches(false);
                localHttpURLConnection.setChunkedStreamingMode(NetUtil.getUploadBufSize(this.appContext));
                localHttpURLConnection.setRequestMethod("POST");
                localHttpURLConnection.setRequestProperty("Connection", "Keep-Alive");
                localHttpURLConnection.setRequestProperty("Content-Type",
                    "multipart/form-data; charset=utf-8; boundary=" + str3 + str1);
                localHttpURLConnection.connect();
                localDataOutputStream = new DataOutputStream(localHttpURLConnection.getOutputStream());
                localDataOutputStream.writeBytes(str2 + str3 + str1);
                String str4 = "";
                if (paramString3 != null) {
                    localDataOutputStream.writeBytes("Content-Disposition: form-data; name=\"app\"" + str1 + str1);
                    localDataOutputStream.writeBytes(paramString3 + str1);
                    localDataOutputStream.writeBytes(str2 + str3 + str1);
                }
                if (paramString4 != null) {
                    localDataOutputStream.writeBytes("Content-Disposition: form-data; name=\"id\"" + str1 + str1);
                    localDataOutputStream.writeBytes(paramString4 + str1);
                    localDataOutputStream.writeBytes(str2 + str3 + str1);
                }
                String str5 = paramString2;
                if (str5.indexOf("/") > 0) {
                    String str6 = str5.substring(0, str5.lastIndexOf("/"));
                    str5 = str5.substring(str5.lastIndexOf("/"));
                    localDataOutputStream.writeBytes("Content-Disposition: form-data; name=\"path\"" + str1 + str1);
                    localDataOutputStream.writeBytes(str6 + str1);
                    localDataOutputStream.writeBytes(str2 + str3 + str1);
                }
                localDataOutputStream.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\"");
                localDataOutputStream.write(str5.getBytes("UTF-8"));
                localDataOutputStream.writeBytes("\"" + str1);
                if ((localFile.getName().endsWith(".3gp")) || (localFile.getName().endsWith(".amr")))
                    str4 = str4 + "Content-Type: audio/3gp" + str1;
                else if (localFile.getName().endsWith(".mp4"))
                    str4 = str4 + "Content-Type: video/mpeg4" + str1;
                else
                    str4 = str4 + "Content-Type: image/png" + str1;
                EWoringLog.d("connstr", str4);
                localDataOutputStream.writeBytes(str4);
                localDataOutputStream.writeBytes(str1);
                int k = localFileInputStream.available();
                int l = Math.min(k, i1);
                byte[] arrayOfByte = new byte[l];
                int j = localFileInputStream.read(arrayOfByte, 0, l);
                EWoringLog.d("Image length", String.valueOf(k));
                try {
                    while (j > 0) {
                        try {
                            i3 += j;
                            localDataOutputStream.write(arrayOfByte, 0, l);
                        } catch (OutOfMemoryError localOutOfMemoryError) {
                        }
                        int i4 = (int) (i3 / i2 * 100.0F);
                        if (i4 > i + 5) {
                            i = i4;
                            EWoringLog.d("HttpFileManager", String.valueOf(i));
                            paramCloudOperationCallback.onProgress(i4);
                        }
                        k = localFileInputStream.available();
                        l = Math.min(k, i1);
                        j = localFileInputStream.read(arrayOfByte, 0, l);
                    }
                } catch (Exception localException2) {
                }
                localDataOutputStream.writeBytes(str1);
                localDataOutputStream.writeBytes(str2 + str3 + str2 + str1);
                int i5 = localHttpURLConnection.getResponseCode();
                String str7 = localHttpURLConnection.getResponseMessage();
                EWoringLog.d("Server Response Code ", String.valueOf(i5));
                EWoringLog.d("Server Response Message", str7);
                if (i5 == 200)
                    EWoringLog.d("http", "file server resp 200 ok");
                else
                    EWoringLog.e("http", "file server resp error, reponse code: " + i5);
                BufferedReader localBufferedReader =
                    new BufferedReader(new InputStreamReader(localHttpURLConnection.getInputStream()));
                String localObject1 = null;
                for (localObject1 = null; (str8 = localBufferedReader.readLine()) != null; localObject1 = str8)
                    EWoringLog.d("CloudFileManager", "RESULT Message: " + str8);
                localBufferedReader.close();
                localFileInputStream.close();
                localDataOutputStream.flush();
                localDataOutputStream.close();
                localDataOutputStream = null;
                if ((localObject1 != null) && (localObject1.contains("Invalid file"))) {
                    paramCloudOperationCallback.onError("Invalid file");
                    localHttpURLConnection.disconnect();
                    return false;
                }
                paramCloudOperationCallback.onProgress(100);
                localHttpURLConnection.disconnect();
                return true;
            } catch (Exception localException1) {
                localException1.printStackTrace();
                throw new EIMException(localException1.getMessage());
            }
        } finally {
            localHttpURLConnection.disconnect();
        }
    }
    
    /**
     * @param strLocalURL
     * @param StrRemoteURL
     * @param appKey
     * @param id
     * @param map
     * @param cloudoperationcallback
     * @return
     * @throws EIMException
     * @throws ClientProtocolException
     * @throws IOException
     */
    private boolean sendFiletoServerHttp(String strLocalURL, String StrRemoteURL, String entcode, String id,
        Map<String, String> paramMap, final CloudOperationCallback callback) throws EIMException,
        ClientProtocolException, IOException {
        // 本地文件
        File file = new File(strLocalURL);
        if (!file.isFile()) {
            EWoringLog.e(_TAG, "上传的文件不存在");
            callback.onError("上传的文件不存在");
            return false;
        }
        // 远程文件地址
        String strRemoteServerURL = (new StringBuilder(String.valueOf(USER_SERVER_URL))).append("/").toString();
        if (entcode != null) {
            strRemoteServerURL =
                (new StringBuilder(String.valueOf(strRemoteServerURL))).append(entcode.replaceFirst("#", "/"))
                    .append("/").toString();
        }
        if (StrRemoteURL.startsWith("http")) {
            strRemoteServerURL = StrRemoteURL;
        } else {
            strRemoteServerURL =
                (new StringBuilder(String.valueOf(strRemoteServerURL))).append(StrRemoteURL).toString();
            
        }
        HttpPost httppost = new HttpPost(strRemoteServerURL);
        CustomMultiPartEntity custommultipartentity =
            new CustomMultiPartEntity(new CustomMultiPartEntity.ProgressListener() {
                
                public void transferred(long transferred) {
                    callback.onProgress((int) ((transferred / totalSize) * 100));
                }
            });
        if (entcode != null) {
            custommultipartentity.addPart("entcode", new StringBody(entcode));
        }
        if (id != null) {
            custommultipartentity.addPart("id", new StringBody(id));
        }
        if (paramMap != null) {
            Iterator<Entry<String, String>> iterator = paramMap.entrySet().iterator();
            while (iterator.hasNext()) {
                Entry<String, String> entry = iterator.next();
                // http头
                httppost.addHeader(entry.getKey(), entry.getValue());
            }
        }
        String foldername = "";
        if (StrRemoteURL.indexOf("/") > 0) {
            // 文件路径
            String strFilePath = StrRemoteURL.substring(0, StrRemoteURL.lastIndexOf("/"));
            // 文件夹名称
            foldername = StrRemoteURL.substring(StrRemoteURL.lastIndexOf("/"));
            custommultipartentity.addPart("path", new StringBody(strFilePath));
        }
        String s7;
        if (file.getName().endsWith(".3gp") || file.getName().endsWith(".amr"))
            s7 = "audio/3gp";
        else
            s7 = "image/png";
        custommultipartentity.addPart("file", new FileBody(file, foldername, s7, "UTF-8"));
        BasicHttpParams basichttpparams = new BasicHttpParams();
        // 设置连接超时时间
        HttpConnectionParams.setConnectionTimeout(basichttpparams, 10000);
        // 设置Socket连接超时
        HttpConnectionParams.setSoTimeout(basichttpparams, 20000);
        // 设置TCP网络延期
        HttpConnectionParams.setTcpNoDelay(basichttpparams, true);
        // 设置文件内容大小
        totalSize = custommultipartentity.getContentLength();
        httppost.setEntity(custommultipartentity);
        HttpClient httpClient = new DefaultHttpClient(basichttpparams);
        HttpResponse response = httpClient.execute(httppost);
        // 文件内容读取
        BufferedReader bufferedreader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        String strError = null;
        StringBuilder stringbuilder = new StringBuilder();
        String strLine;
        while ((strLine = bufferedreader.readLine()) != null) {
            EWoringLog.d(_TAG, (new StringBuilder("RESULT Message: ")).append(strLine).toString());
            strError = strLine;
            stringbuilder.append(strLine);
        }
        bufferedreader.close();
        EWoringLog.d(_TAG, (new StringBuilder("server resp:")).append(response.getStatusLine()).toString());
        if (strError == null || !strError.contains("Invalid file")) {
            callback.onError("Invalid file");
            return false;
        }
        try {
            callback.onProgress(100);
            callback.onSuccess(stringbuilder.toString());
        } catch (Exception exception) {
            throw new EIMException(exception.getMessage());
        }
        return true;
    }
    
    public void uploadFileInBackground(final String strLocalURL, final String StrRemoteURL, final String entcode,
        final String id, final Map<String, String> paramMap, final CloudOperationCallback callback) {
        Thread thread = new Thread() {
            
            @Override
            public void run() {
                try {
                    // 上传附件到服务器
                    sendFiletoServerHttp(strLocalURL, StrRemoteURL, entcode, id, paramMap, callback);
                } catch (Exception e) {
                    EWoringLog.e(_TAG, "上传附件失败" + e.getMessage());
                }
            };
        };
        
        thread.start();
    }
    
    /**
     * 上传文件
     * 
     * @param strLocalURL 文件本地地址
     * @param strRemoteURL 远程地址
     * @param appkey 企业代码
     * @param paramString4
     * @param paramMap 参数
     * @param CloudOperationCallback 回调函数
     */
    public void uploadFile(String strLocalURL, String strRemoteURL, String appkey, String paramString4,
        Map<String, String> paramMap, CloudOperationCallback CloudOperationCallback) {
        try {
            // 上传文件到服务器
            sendFiletoServerHttp(strLocalURL, strRemoteURL, appkey, paramString4, paramMap, CloudOperationCallback);
        } catch (Exception localException) {
            localException.printStackTrace();
            CloudOperationCallback.onError(localException.toString());
        }
    }
    
    /**
     * 下载文件
     */
    public void downloadFile(String strRemoteURL, String strLocalFilePath, String entcode, String folder,
        Map<String, String> paramMap, CloudOperationCallback callback) {
        String strTempRemoteURL = USER_SERVER_URL + "/";
        if (entcode != null) {
            strTempRemoteURL = strTempRemoteURL + entcode.replaceFirst("#", "/") + "/";
        }
        if (folder != null) {
            strTempRemoteURL = strTempRemoteURL + folder;
        }
        strTempRemoteURL = strTempRemoteURL + strRemoteURL;
        if (strRemoteURL.startsWith("http")) {
            strTempRemoteURL = strRemoteURL;
        } else {
            strTempRemoteURL = strTempRemoteURL + strRemoteURL;
        }
        downloadFile(strTempRemoteURL, strLocalFilePath, paramMap, callback);
    }
    
    /**
     * 下载缩略图
     * 
     * @param strRemoteURL 远程地址
     * @param strLocalFilePath 本地地址
     * @param entcode 企业代码
     * @param folder 文件夹名称
     * @param size 文件大小
     * @param isSave
     * @param paramMap
     * @param paramCloudOperationCallback
     */
    public void downloadThumbnailFile(String strRemoteURL, String strLocalFilePath, String entcode, String folder,
        int size, boolean isSave, Map<String, String> paramMap, CloudOperationCallback paramCloudOperationCallback) {
        String strTempRemoteURL = USER_SERVER_URL;
        if (entcode != null) {
            strTempRemoteURL = strTempRemoteURL + entcode.replaceFirst("#", "/") + "/";
        }
        if (folder != null) {
            strTempRemoteURL = strTempRemoteURL + folder;
        }
        if (size > 0) {
            strTempRemoteURL = strTempRemoteURL + "&size=" + size;
        }
        if (isSave) {
            strTempRemoteURL = strTempRemoteURL + "&save=true";
        }
        if (strRemoteURL.startsWith("http:")) {
            strTempRemoteURL = strRemoteURL;
        } else {
            strTempRemoteURL = strTempRemoteURL + strRemoteURL;
        }
        downloadFile(strTempRemoteURL, strLocalFilePath, paramMap, paramCloudOperationCallback);
    }
    
    /**
     * 下载缩略图
     * 
     * @param strRemoteURL
     * @param strLocalFilePath
     * @param entcode
     * @param folder
     * @param paramMap
     * @param callback
     */
    public void downloadThumbnailFile(String strRemoteURL, String strLocalFilePath, String entcode, String folder,
        Map<String, String> paramMap, CloudOperationCallback callback) {
        // 下载缩略图
        downloadThumbnailFile(strRemoteURL, strLocalFilePath, entcode, folder, 0, false, paramMap, callback);
    }
    
    /**
     * 下载附件
     * 
     * @param strRemoteURL 远程地址
     * @param strLocalFilePath 本地地址
     * @param paramMap
     * @param callback
     */
    public void downloadFile(String strRemoteURL, String strLocalFilePath, Map<String, String> paramMap,
        CloudOperationCallback callback) {
        // 远程文件地址
        if (strRemoteURL.contains("+")) {
            strRemoteURL = strRemoteURL.replaceAll("+", "%2B");
        }
        if (strRemoteURL.contains("#")) {
            strRemoteURL = strRemoteURL.replaceAll("#", "%23");
        }
        EWoringLog.d(_TAG, "download file: remote: " + strRemoteURL + " , local: " + strLocalFilePath);
        File localFile = new File(strLocalFilePath);
        // 创建上级文件夹
        if (!(localFile.getParentFile().exists())) {
            localFile.mkdirs();
        }
        int length = 0;
        int j = 0;
        HttpClient httpClient = new DefaultHttpClient();
        InputStream inputStream = null;
        FileOutputStream fileOutputStream = null;
        
        try {
            HttpGet httpGet = new HttpGet(strRemoteURL);
            if (paramMap != null) {
                Iterator<Entry<String, String>> iter = paramMap.entrySet().iterator();
                while (iter.hasNext()) {
                    Entry<String, String> entry = iter.next();
                    httpGet.addHeader(entry.getKey(), entry.getValue());
                }
            }
            BasicHttpParams basicHttpParams = new BasicHttpParams();
            HttpConnectionParams.setConnectionTimeout(basicHttpParams, 10000);
            HttpConnectionParams.setSoTimeout(basicHttpParams, 20000);
            httpGet.setParams(basicHttpParams);
            HttpResponse response = httpClient.execute(httpGet);
            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    // 文件大小
                    long size = entity.getContentLength();
                    // 文件内容
                    inputStream = entity.getContent();
                    fileOutputStream = new FileOutputStream(new File(strLocalFilePath));
                    // 下载速度消息
                    int downloadSize = NetUtil.getDownloadBufSize(this.appContext);
                    byte[] arrayOfByte = new byte[downloadSize];
                    // 文件大小
                    long filesize = 0;
                    while ((length = inputStream.read(arrayOfByte)) != -1) {
                        filesize += length;
                        int count = (int) (filesize * 100 / size);
                        if ((count == 100) || (count > j + 5)) {
                            j = count;
                            if (callback != null) {
                                callback.onProgress(j);
                            }
                        }
                        fileOutputStream.write(arrayOfByte, 0, length);
                    }
                    if (callback != null)
                        callback.onSuccess(null);
                }
            } else if (callback != null) {
                callback.onError(String.valueOf(response.getStatusLine().getStatusCode()));
            }
        } catch (Exception e) {
            if (callback != null)
                callback.onError(e.getMessage());
            try {
                if (fileOutputStream != null) {
                    fileOutputStream.close();
                }
                if (inputStream == null) {
                    return;
                }
                inputStream.close();
            } catch (Exception localException3) {
            }
        } finally {
            try {
                if (fileOutputStream != null) {
                    fileOutputStream.close();
                }
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (Exception localException4) {
            }
        }
    }
    
    public void deleteFileInBackground(final String entcode, final String strRemoteURL, String paramString3,
        final CloudOperationCallback callback) {
        Thread thread = new Thread() {
            
            @Override
            public void run() {
                String strCharRN = "\r\n";
                String strChar_ = "--";
                String strChar = "*****";
                String strTempRemoteURL = "";
                strTempRemoteURL =
                    (new StringBuilder(String.valueOf(HttpFileManager.USER_SERVER_URL))).append("/").toString();
                if (entcode != null) {
                    strTempRemoteURL =
                        (new StringBuilder(strTempRemoteURL)).append(entcode.replaceFirst("#", "/")).append("/")
                            .toString();
                }
                if (strRemoteURL.startsWith("http")) {
                    strTempRemoteURL = strRemoteURL;
                } else {
                    strTempRemoteURL = (new StringBuilder(strTempRemoteURL)).append(strRemoteURL).toString();
                }
                try {
                    URL url = new URL(strTempRemoteURL);
                    HttpURLConnection httpurlconnection = (HttpURLConnection) url.openConnection();
                    httpurlconnection.setDoInput(true);
                    httpurlconnection.setDoOutput(true);
                    httpurlconnection.setUseCaches(false);
                    httpurlconnection.setRequestMethod("POST");
                    httpurlconnection.setRequestProperty("Connection", "Keep-Alive");
                    httpurlconnection.setRequestProperty("ENCTYPE", "multipart/form-data");
                    httpurlconnection.setRequestProperty("Content-Type", (new StringBuilder(
                        "multipart/form-data;boundary=")).append(strChar).toString());
                    httpurlconnection.setRequestProperty("file", strRemoteURL);
                    DataOutputStream dataoutputstream = new DataOutputStream(httpurlconnection.getOutputStream());
                    dataoutputstream.writeBytes((new StringBuilder(String.valueOf(strChar_))).append(strChar)
                        .append(strCharRN).toString());
                    if (entcode != null) {
                        dataoutputstream.writeBytes((new StringBuilder("Content-Disposition: form-data; name=\"app\""))
                            .append(strCharRN).append(strCharRN).toString());
                        dataoutputstream.writeBytes((new StringBuilder(entcode)).append(strCharRN).toString());
                        dataoutputstream.writeBytes((new StringBuilder(strChar_)).append(strChar).append(strCharRN)
                            .toString());
                    }
                    dataoutputstream.writeBytes((new StringBuilder(
                        "Content-Disposition: form-data; name=\"file\";filename=\"")).append(strRemoteURL).append("\"")
                        .append(strCharRN).toString());
                    dataoutputstream.writeBytes(strCharRN);
                    BufferedReader bufferedreader =
                        new BufferedReader(new InputStreamReader(httpurlconnection.getInputStream()));
                    String s7;
                    while ((s7 = bufferedreader.readLine()) != null)
                        EWoringLog.d(_TAG, (new StringBuilder("RESULT Message: ")).append(s7).toString());
                    bufferedreader.close();
                    dataoutputstream.close();
                    httpurlconnection.disconnect();
                    if (callback != null) {
                        callback.onSuccess(null);
                    }
                } catch (Exception exception) {
                    if (callback != null) {
                        callback.onError(exception.toString());
                    }
                }
            }
        };
        thread.start();
    }
}
